package cn.edu.sziit.bbs.controller;

import cn.edu.sziit.bbs.model.User;
import cn.edu.sziit.bbs.service.UserService;
import cn.edu.sziit.bbs.util.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//login.jsp
@Controller
public class LoginController {
    @Autowired
    UserService userService;

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String showLogin() {

        return "login";
    }

    /**
     * 登录验证
     *
     * @param user
     * @param code
     * @param session
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;" +
            "charset=UTF-8")
    public Map<String, String> loginCheck(User user, String code, HttpSession session, Model model) {

        Map<String, String> map = new HashMap<>();

        if (!code.equals(session.getAttribute("randomString"))) {
            System.out.println(code);
            System.out.println(session.getAttribute("randomString"));
            System.out.println("验证码错误");
            map.put("info", "验证码错误");
            return map;

        }
        String info = userService.userCheck(user);
        map.put("info", info);
        model.addAttribute("info", info);
        if (info.equals("登录成功") || info.equals("管理员登陆成功")) {
            session.setAttribute("user", userService.selectByUsername(user.getUserName()));
        }
        return map;
    }

    @RequestMapping(value = "/admin/login", method = RequestMethod.GET)
    public String showIndexLogin() {

        return "login";
    }

}
